using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Reflection;

namespace JGSY.CMS.LowCode.Platform.Infrastructure.Configuration.ServiceModules
{
    /// <summary>
    /// 服务模块注册器
    /// 负责自动发现和注册所有服务模块，支持基于权限的动态控制
    /// </summary>
    public static class ServiceModuleRegistry
    {
        private static readonly List<IServiceModule> _modules = new();
        private static bool _modulesLoaded = false;
        private static ModulePermissionManager? _permissionManager;

        /// <summary>
        /// 注册所有服务模块（支持权限控制）
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="configuration">配置对象</param>
        /// <param name="fastMode">是否为快速启动模式</param>
        public static void RegisterAllModules(IServiceCollection services, IConfiguration configuration, bool fastMode = false)
        {
            if (!_modulesLoaded)
            {
                LoadModules();
                _modulesLoaded = true;
            }

            // 初始化权限管理器
            _permissionManager = new ModulePermissionManager(configuration);
            
            // 将权限管理器注册为单例服务
            services.AddSingleton(_permissionManager);

            var applicableModules = _modules
                .Where(m => ShouldLoadModule(m, configuration, fastMode))
                .Where(m => m.ValidateConfiguration(configuration))
                .OrderBy(m => m.Priority)
                .ToList();

            foreach (var module in applicableModules)
            {
                try
                {
                    var stopwatch = System.Diagnostics.Stopwatch.StartNew();
                    
                    // 检查权限并决定加载方式
                    if (HasModulePermission(module))
                    {
                        // 有权限 - 加载完整功能
                        module.ConfigureServices(services, configuration);
                        Infrastructure.Configuration.StartupLogger.LogStartupMilestone($"✅ 模块 {module.ModuleName} 完整功能注册完成，耗时: {stopwatch.ElapsedMilliseconds}ms");
                    }
                    else if (module.IsCriticalModule)
                    {
                        // 关键模块但权限被禁用 - 加载基本功能
                        module.ConfigureMinimalServices(services, configuration);
                        Infrastructure.Configuration.StartupLogger.LogStartupMilestone($"⚠️ 关键模块 {module.ModuleName} 精简功能注册完成（权限受限），耗时: {stopwatch.ElapsedMilliseconds}ms");
                    }
                    else
                    {
                        // 非关键模块且权限被禁用 - 跳过
                        Infrastructure.Configuration.StartupLogger.LogStartupMilestone($"❌ 模块 {module.ModuleName} 已跳过（权限禁用）");
                        continue;
                    }
                    
                    stopwatch.Stop();
                }
                catch (Exception ex)
                {
                    Infrastructure.Configuration.StartupLogger.LogStartupError($"模块 {module.ModuleName} 注册失败", ex);
                    throw;
                }
            }

            // 记录权限状态摘要
            LogPermissionSummary();
        }

        /// <summary>
        /// 检查模块是否应该加载
        /// </summary>
        private static bool ShouldLoadModule(IServiceModule module, IConfiguration configuration, bool fastMode)
        {
            // 快速模式检查
            if (fastMode && !module.LoadInFastMode)
            {
                return false;
            }

            return true;
        }

        /// <summary>
        /// 检查模块是否有权限
        /// </summary>
        private static bool HasModulePermission(IServiceModule module)
        {
            if (_permissionManager == null)
                return true;

            return _permissionManager.HasServiceModulePermission(module.RequiredPermission);
        }

        /// <summary>
        /// 记录权限状态摘要
        /// </summary>
        private static void LogPermissionSummary()
        {
            if (_permissionManager == null)
                return;

            var permissions = _permissionManager.GetAllPermissions();
            var serviceModules = (Dictionary<string, object>)permissions["ServiceModules"];
            
            var enabledCount = serviceModules.Values.Count(v => (bool)v);
            var totalCount = serviceModules.Count;
            
            StartupLogger.LogStartupMilestone($"📊 模块权限摘要: {enabledCount}/{totalCount} 个服务模块已启用");
        }

        /// <summary>
        /// 动态更新模块权限
        /// </summary>
        /// <param name="permission">模块权限</param>
        /// <param name="enabled">是否启用</param>
        public static void UpdateModulePermission(ModulePermission permission, bool enabled)
        {
            _permissionManager?.SetServiceModulePermission(permission, enabled);
        }

        /// <summary>
        /// 获取当前权限管理器
        /// </summary>
        /// <returns>权限管理器实例</returns>
        public static ModulePermissionManager? GetPermissionManager()
        {
            return _permissionManager;
        }

        /// <summary>
        /// 加载所有服务模块
        /// </summary>
        private static void LoadModules()
        {
            var moduleTypes = Assembly.GetExecutingAssembly()
                .GetTypes()
                .Where(t => typeof(IServiceModule).IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract)
                .ToList();

            foreach (var moduleType in moduleTypes)
            {
                try
                {
                    var module = (IServiceModule)Activator.CreateInstance(moduleType)!;
                    _modules.Add(module);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException($"无法创建服务模块实例: {moduleType.Name}", ex);
                }
            }
        }

        /// <summary>
        /// 手动注册服务模块
        /// </summary>
        /// <param name="module">服务模块</param>
        public static void RegisterModule(IServiceModule module)
        {
            if (!_modules.Contains(module))
            {
                _modules.Add(module);
            }
        }

        /// <summary>
        /// 获取已注册的模块列表
        /// </summary>
        /// <returns>模块列表</returns>
        public static IReadOnlyList<IServiceModule> GetRegisteredModules()
        {
            if (!_modulesLoaded)
            {
                LoadModules();
                _modulesLoaded = true;
            }
            return _modules.AsReadOnly();
        }
    }
}
